package org.yuangu.privacyfinance.activities.dialog;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.privacy.accountmgr.R;
import com.privacy.accountmgr.databinding.DialogTransactionBinding;

import org.joda.time.LocalDate;
import org.yuangu.privacyfinance.activities.helper.CurrencyInputFilter;
import org.yuangu.privacyfinance.activities.viewmodel.TransactionDialogViewModel;
import org.yuangu.privacyfinance.domain.model.Account;
import org.yuangu.privacyfinance.domain.model.Category;
import org.yuangu.privacyfinance.domain.model.RepeatingTransaction;
import org.yuangu.privacyfinance.domain.model.Transaction;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

public class TransactionDialog extends AppCompatDialogFragment {
    public static final String EXTRA_CATEGORY_ID = "org.secuso.privacyfriendlyfinance.EXTRA_CATEGORY_ID";
    public static final String EXTRA_ACCOUNT_ID = "org.secuso.privacyfriendlyfinance.EXTRA_ACCOUNT_ID";
    public static final String EXTRA_TRANSACTION_ID = "org.secuso.privacyfriendlyfinance.EXTRA_TRANSACTION_ID";

    private androidx.appcompat.app.AlertDialog dialog;
    private View view;
    private EditText editTextAmount;
    private TextView editTextDate;
    private Spinner categorySpinner;
    private Spinner accountSpinner;
    private TextView tvRepeating;
    private ImageView ivRepeating;

    private TransactionDialogViewModel viewModel;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(getActivity());

        viewModel = ViewModelProviders.of(this).get(TransactionDialogViewModel.class);

        final DialogTransactionBinding binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.dialog_transaction, null, false);
        view = binding.getRoot();
        builder.setView(view);

        editTextAmount = view.findViewById(R.id.dialog_transaction_amount);
        editTextDate = view.findViewById(R.id.dialog_transaction_date);
        categorySpinner = view.findViewById(R.id.category_spinner);
        accountSpinner = view.findViewById(R.id.account_spinner);
        tvRepeating = view.findViewById(R.id.textView_repeating);
        ivRepeating = view.findViewById(R.id.imageView_repeating);
        viewModel.setCurrencyColors(getResources().getColor(R.color.green), getResources().getColor(R.color.red));

        long transactionId = getArguments().getLong(EXTRA_TRANSACTION_ID, -1L);

        if (transactionId >= 0) {
            builder.setTitle(R.string.dialog_transaction_edit_title);
        } else {
            builder.setTitle(R.string.dialog_transaction_create_title);
        }
        if (viewModel.getTransaction() == null) {
            viewModel.setTransactionId(transactionId).observe(this, new Observer<Transaction>() {
                @Override
                public void onChanged(@Nullable Transaction transaction) {
                    // Is it a transaction dummy?
                    if (transaction.getId() == null) {
                        Log.d("acc id", getArguments().getLong(EXTRA_ACCOUNT_ID, -1L) + "");
                        transaction.setAccountId(getArguments().getLong(EXTRA_ACCOUNT_ID, -1L));
                        transaction.setCategoryId(getArguments().getLong(EXTRA_CATEGORY_ID, -1L));
                    }
                    viewModel.setTransaction(transaction);
                    bindRepeatingTransaction();
                    binding.setViewModel(viewModel);
                }
            });
        } else {
            bindRepeatingTransaction();
            binding.setViewModel(viewModel);
        }

        viewModel.getAllAccounts().observe(this, new Observer<List<Account>>() {
            @Override
            public void onChanged(@Nullable List<Account> accounts) {
                accountSpinner.setAdapter(new ArrayAdapter<>(getActivity(), R.layout.support_simple_spinner_dropdown_item, accounts));
                accountSpinner.setSelection(viewModel.getAccountIndex());
            }
        });

        viewModel.getAllCategories().observe(this, new Observer<List<Category>>() {
            @Override
            public void onChanged(@Nullable List<Category> categories) {
                categorySpinner.setAdapter(new NullableArrayAdapter<>(getActivity(), R.layout.support_simple_spinner_dropdown_item, categories));
                categorySpinner.setSelection(viewModel.getCategoryIndex());
            }
        });

        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                viewModel.cancel();
            }
        });

        builder.setPositiveButton(R.string.submit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                viewModel.submit();
            }
        });

        editTextAmount.setFilters(new InputFilter[]{new CurrencyInputFilter()});

        editTextDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openDatePickerTransactionDate();
            }
        });

        dialog = builder.create();
        return dialog;
    }

    private void openDatePickerTransactionDate() {
        openDatePicker(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                viewModel.setDate(new LocalDate(year, month + 1, dayOfMonth));
            }
        });
    }

    private void bindRepeatingTransaction() {
        if (viewModel.getRepeatingTransaction() != null) {
            viewModel.getRepeatingTransaction().observe(this, new Observer<RepeatingTransaction>() {
                @Override
                public void onChanged(@Nullable RepeatingTransaction repeatingTransaction) {
                    if (repeatingTransaction == null) {
                        tvRepeating.setVisibility(View.INVISIBLE);
                        ivRepeating.setVisibility(View.INVISIBLE);
                    } else {
                        tvRepeating.setText(repeatingTransaction.getName());
                        tvRepeating.setVisibility(View.VISIBLE);
                        ivRepeating.setVisibility(View.VISIBLE);
                    }
                }
            });
        } else {
            tvRepeating.setVisibility(View.INVISIBLE);
            ivRepeating.setVisibility(View.INVISIBLE);
        }
    }

    private void openDatePicker(DatePickerDialog.OnDateSetListener listener) {
        LocalDate date = viewModel.getDate();
        new DatePickerDialog(getContext(), listener, date.getYear(), date.getMonthOfYear() - 1, date.getDayOfMonth()).show();
        dialog.show();
    }

    public class NullableArrayAdapter<T> extends ArrayAdapter<T> {
        private int resource;
        private int fieldId = 0;
        private LayoutInflater inflater;
        private String nullPlaceholderString;

        public NullableArrayAdapter(Context context, int resource) {
            super(context, resource);
            this.resource = resource;
            inflater = LayoutInflater.from(context);
        }

        public NullableArrayAdapter(Context context, int resource, int textViewResourceId) {
            super(context, resource, textViewResourceId);
            this.resource = resource;
            fieldId = textViewResourceId;
            inflater = LayoutInflater.from(context);
        }

        public NullableArrayAdapter(Context context, int resource, T[] objects) {
            super(context, resource, objects);
            this.resource = resource;
            inflater = LayoutInflater.from(context);
        }

        public NullableArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) {
            super(context, resource, textViewResourceId, objects);
            this.resource = resource;
            fieldId = textViewResourceId;
            inflater = LayoutInflater.from(context);
        }

        public NullableArrayAdapter(Context context, int resource, List<T> objects) {
            super(context, resource, objects);
            this.resource = resource;
            inflater = LayoutInflater.from(context);
        }

        public NullableArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects) {
            super(context, resource, textViewResourceId, objects);
            this.resource = resource;
            fieldId = textViewResourceId;
            inflater = LayoutInflater.from(context);
        }

        public NullableArrayAdapter<T> setNullPlaceholderString(String nullPlaceholderString) {
            this.nullPlaceholderString = nullPlaceholderString;
            return NullableArrayAdapter.this;
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            return createViewFromResource(inflater, position, convertView, parent, resource);
        }

        // This method is private in android.widget.ArrayAdapter. IMHO it should be protected.
        protected @NonNull
        View createViewFromResource(@NonNull LayoutInflater inflater, int position,
                                    @Nullable View convertView, @NonNull ViewGroup parent, int resource) {
            final View view;
            final TextView text;
            if (convertView == null) {
                view = inflater.inflate(resource, parent, false);
            } else {
                view = convertView;
            }
            try {
                if (fieldId == 0) {
                    //  If no custom field is assigned, assume the whole resource is a TextView
                    text = (TextView) view;
                } else {
                    //  Otherwise, find the TextView field within the layout
                    text = view.findViewById(fieldId);
                    if (text == null) {
                        throw new RuntimeException("Failed to find view with ID "
                                + getContext().getResources().getResourceName(fieldId)
                                + " in item layout");
                    }
                }
            } catch (ClassCastException e) {
                Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
                throw new IllegalStateException(
                        "ArrayAdapter requires the resource ID to be a TextView", e);
            }
            final T item = getItem(position);
            text.setTextColor(getContext().getResources().getColor(android.R.color.primary_text_light));
            if (item == null) {
                if (nullPlaceholderString == null) {
                    nullPlaceholderString = getContext().getResources().getString(R.string.none);
                }
                text.setText(nullPlaceholderString);
                text.setTextColor(getContext().getResources().getColor(android.R.color.tertiary_text_light));
            } else if (item instanceof CharSequence) {
                text.setText((CharSequence) item);
            } else {
                text.setText(item.toString());
            }
            return view;
        }

        //    @Override
        //    public void setDropDownViewResource(@LayoutRes int resource) {
        //        dropDownResource = resource;
        //    }

        @Override
        public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            //        final LayoutInflater ddInflater = mDropDownInflater == null ? inflater : mDropDownInflater;
            return createViewFromResource(inflater, position, convertView, parent, resource);
        }
    }
}
